package com.regedit.aplicacion.dao;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * The Class DatabaseHelper.
 */
public class DatabaseHelper extends SQLiteOpenHelper {

	/** The Constants. */
	public static final String DATABASE_NAME = "android.db";
	private static final int DATABASE_VERSION = 1;
	private static final String SQL_DROP = "DROP TABLE IF EXISTS ";
	public static final String SQL_DELETE = "DELETE FROM ";

	/**
	 * Constructor - Receives the context to allow the database to be
	 * opened/created.
	 * 
	 * @param context
	 *            the context
	 */
	public DatabaseHelper(final Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	/**
	 * Called when the Database is first created.
	 * 
	 * @param db
	 *            The SQLite database to create the tables into
	 */
	@Override
	public void onCreate(final SQLiteDatabase database) {
		try {
			database.execSQL(EntityDao.CREATE_TABLE);

		} catch (SQLException e) {
			Log.e("error on createTables", e.getMessage());
		} catch (Exception e) {
			Log.e("error on createTables", e.getMessage());
		}
	}

	/**
	 * Called when the Database is opened.
	 * 
	 * @param db
	 *            The SQLite database to create the tables into
	 */
	@Override
	public void onOpen(final SQLiteDatabase database) {
		super.onOpen(database);
		createTables(database);
	}

	/**
	 * Update the SQLite to its newest version. All data is lost.
	 * 
	 * @param db
	 *            the database
	 * @param oldVersion
	 *            the old version
	 * @param newVersion
	 *            the new version
	 */
	@Override
	public void onUpgrade(final SQLiteDatabase database, final int oldVersion,
			final int newVersion) {
		Log.w("DATABASE HELPER", "Upgrading database from version "
				+ oldVersion + " to " + newVersion
				+ ", which will destroy all old data");
		// Drop Tables
		alterTables(database, SQL_DROP);
		onCreate(database);
	}

	/**
	 * Create all the tables needed for the app to work.
	 * 
	 * @param db
	 *            The SQLite database to create the tables into
	 */
	private void createTables(final SQLiteDatabase database) {
		
	}

	// TODO:javadoc
	private void alterTables(final SQLiteDatabase database, final String sSql) {
		try {
			database.execSQL(sSql + EntityDao.TABLE_NAME);

		} catch (SQLException e) {
			Log.e("error on alterTables", e.getMessage());
		} catch (Exception e) {
			Log.e("error on alterTables", e.getMessage());
		}
	}

	/**
	 * Delete all data.
	 */
	public void deleteDataFromTables() {
		try {
			final SQLiteDatabase database = getWritableDatabase();
			alterTables(database, SQL_DELETE);

		} catch (SQLException e) {
			Log.e("error on deleteDataFromTables", e.getMessage());
		}
	}
}
